package dtime

import (
	"common/models"
	"fmt"
	"go.uber.org/zap"
	"strings"
	"sync"
	"time"
	"video/pkg/dao/redis"
)

var VideoTask VideoUpdateTask

func init() {
	VideoTask.data = make(map[string]string)
}

type VideoUpdateTask struct {
	data  map[string]string
	mutex sync.Mutex
	size  int
}

func (d VideoUpdateTask) AppendData(key, value string) {
	d.mutex.Lock()
	d.data[key] = value
	d.size++
	d.mutex.Unlock()
}
func (d VideoUpdateTask) DeleteAndGetOne() (key, value string) {
	d.mutex.Lock()
	for k, v := range d.data {
		key = k
		value = v
		continue
	}
	delete(d.data, key)
	d.size--
	d.mutex.Unlock()
	return
}
func (d VideoUpdateTask) DeleteAndGetAllData() (res map[string]string) {
	res = make(map[string]string)
	d.mutex.Lock()
	for key, value := range d.data {
		res[key] = value
	}
	d.data = make(map[string]string, 0)
	d.mutex.Unlock()
	return
}
func (s ServerTime) UpdateVideoInfo() {
	var (
		str string
	)
	taskIds := make(map[string]string)
	//判断任务的数量 <20直接全部读取
	if VideoTask.size < 20 {
		taskIds = VideoTask.DeleteAndGetAllData()
	} else {
		//读取20条
		for i := 0; i < 20; i++ {
			key, value := VideoTask.DeleteAndGetOne()
			taskIds[key] = value
		}
	}
	str = fmt.Sprintf("Update Task Start time %v", time.Now())
	if len(taskIds) == 0 {
		return
	}
	zap.L().Info(str)
	for key, value := range taskIds {
		zap.L().Error("--------ID" + key)
		//读取redis数据 -- 喜欢的数量 | 不喜欢的数量 | 收藏的数量
		info, err := s.R.GetString(redis.VideoInfoLikeOrNo + key)
		if err != nil {
			//没有读到直接结束
			zap.L().Info("DTime: UpdateVideoInfo s.R.GetString", zap.Error(err))
			continue
		}
		countListStr := strings.Split(info, models.SplitFormat)
		//查这条视频的记录
		videoInfo, err := s.M.VideoInfoQueryById(value)
		if err != nil {
			//没有读到退出
			zap.L().Error("DTime: UpdateVideoInfo s.M.VideoInfoQueryById", zap.Error(err))
			continue
		}
		videoInfo.LikePeopleCount = countListStr[0]
		videoInfo.DisLikePeopleCount = countListStr[1]
		videoInfo.CollectionPeopleCount = countListStr[2]
		//更新这一条记录
		if err := s.M.VideoInfoSaveById(videoInfo); err != nil {
			//没有读到退出
			zap.L().Error("DTime: UpdateVideoInfo s.M.VideoInfoSaveById", zap.Error(err))
			continue
		}
	}
	str = fmt.Sprintf("Update Task End time %v", time.Now())
	zap.L().Info(str)
}
